package com.be.beadmin.system.impl.ProjectDesignServiceImpl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.basicData.dto.output.UserEx;
import com.be.beadmin.basicData.service.UserService;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.design.entity.BopTotal;
import com.be.beadmin.design.entity.StandProduct;
import com.be.beadmin.design.repository.*;
import com.be.beadmin.design.service.BopTotalService;
import com.be.beadmin.design.service.StandProductService;
import com.be.beadmin.design.service.UnStandProductProcessInfoService;
import com.be.beadmin.project.dto.input.BatchProductDto;
import com.be.beadmin.project.dto.input.ProductInfoDto;
import com.be.beadmin.project.dto.input.ProductInfosDto;
import com.be.beadmin.project.entity.BatchProduct;
import com.be.beadmin.project.entity.Info;
import com.be.beadmin.project.entity.ProductInfo;
import com.be.beadmin.project.mapper.BatchProductMapper;
import com.be.beadmin.project.mapper.ProductInfoMapper;
import com.be.beadmin.project.repository.BatchProductRepository;
import com.be.beadmin.project.repository.InfoRepository;
import com.be.beadmin.project.repository.ProductInfoRepository;
import com.be.beadmin.project.service.TeamInfoService;
import com.be.beadmin.project.service.TeamService;
import com.be.beadmin.service.entity.DictData;
import com.be.beadmin.service.entity.DictType;
import com.be.beadmin.service.repository.DictDataRepository;
import com.be.beadmin.service.service.DictTypeService;
import com.be.beadmin.service.service.SerialNumberService;
import com.be.beadmin.system.service.ProjectDesignSevice.BatchProductPdService;
import com.be.beadmin.system.service.ProjectDesignSevice.ProductInfoPdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @author: Jiaming Zheng
 * @Date: Create in 9:47 2023/6/20
 * @Modified By:
 **/
@Service
public class ProductInfoPdServiceImpl implements ProductInfoPdService {

    @Autowired
    private ProductInfoRepository productInfoRepository;

    @Autowired
    private UserService userService;


    @Autowired
    private TeamInfoService teamInfoService;

    @Autowired
    private TeamService teamService;
    @Autowired
    private BopTotalService bopTotalService;
    @Autowired
    private BatchProductPdService batchProductPdService;

    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private BatchProductRepository batchProductRepository;
    @Autowired
    private BatchProductMapper batchProductMapper;

    @Autowired
    private StandProductRepository standProductRepository;

    @Autowired
    private StandProductService standProductService;

    @Autowired
    private StandProductProcessInfoRepository standProductProcessInfoRepository;
    @Autowired
    private StandFileInfoRepository standFileInfoRepository;
    @Autowired
    private InfoRepository infoRepository;

    @Autowired
    private DictTypeService dictTypeService;

    @Autowired
    private DictDataRepository dictDataRepository;

    @Autowired
    private SerialNumberService serialNumberService;
    /**
     * 发布一条柜体信息
     *
     * @param productInfoId
     * @return
     */
    @Override
    public int releaseProductInfo(String productInfoId) {
        if (productInfoId == null){
            return -12;
        }
        ProductInfo productInfo = productInfoRepository.findProductInfoById(productInfoId);
        Info info = infoRepository.findInfoByIdAndDelete(productInfo.getInfoId(),0);
//        productInfo = productInfoMapper.toEntity(productInfoDto);
        if (productInfo.getIsPublished()==1){
            return -10;
        }
        if (Objects.equals(info.getContractState(), "未发布")){
            return -11;
        }


        BatchProductDto batchProductDto = new BatchProductDto();
        batchProductDto.setInfoId(productInfo.getInfoId());
        batchProductDto.setProductCode(productInfo.getProductCode());
        batchProductDto.setProductType(productInfo.getProductType());
        batchProductDto.setBatchPlanId("-1");
        batchProductDto.setIsStandard(BigDecimal.valueOf(productInfo.getIsStandard()));
        batchProductDto.setProjectName(info.getProjectName());
        batchProductDto.setProjectCode(info.getProjectCode());
        System.out.println("是否为标准柜体：" + productInfo.getIsStandard());
        if (productInfo.getIsStandard() == 1) { //标准柜体
            batchProductDto.setStandardProductCode(productInfo.getStandTypeCode());
            StandProduct standProduct = standProductRepository.findStandProductByStandTypeCodeAndDelete(productInfo.getStandTypeCode(),0);
            if (standProduct == null ) throw new BeadminException("未找到该标准柜体");
            //设置图纸 BOM 和BOP
            if (standProduct.getStandBomFileCode() != null) {
                //将BOM添加到这个表中 productBomOverview

                batchProductDto.setBomId(standProduct.getStandBomFileCode());
                batchProductDto.setIsBomUploaded(BigDecimal.valueOf(1));
            }
            if (standProduct.getStandDrawingFileCode() != null) {
                //将图纸添加到这个表中 productDrawingOverview

                batchProductDto.setDrawingId(standProduct.getStandDrawingFileCode());
                batchProductDto.setIsDrawingUploaded(BigDecimal.valueOf(1));
            }
            if (standProduct.getBopCode() != null) {

                batchProductDto.setBopCode(standProduct.getBopCode());
                batchProductDto.setIsBomUploaded(BigDecimal.valueOf(1));
                // 将每道工序添加到这个表中 productManufactOverview

            }
            if (batchProductDto.getBomId() != null && batchProductDto.getDrawingId() != null && batchProductDto.getBopCode() != null) {
                batchProductDto.setReviewState(BigDecimal.valueOf(1));
            }
            //            batchProductxDto
        }

        BatchProduct batchProduct = batchProductMapper.toEntity(batchProductDto);
        batchProductRepository.save(batchProduct);
        productInfo.setIsPublished(1);
        productInfoRepository.save(productInfo);

        return 0;
    }
    /**
     * 发布一条柜体信息
     *
     * @param productInfoEx
     * @return
     */
    @Override
    public int releaseProductInfo(ProductInfo productInfoEx) {
        if (productInfoEx == null){
            return -12;
        }
        ProductInfo productInfo = productInfoRepository.findProductInfoById(productInfoEx.getId());
        Info info = infoRepository.findInfoByIdAndDelete(productInfo.getInfoId(),0);
//        productInfo = productInfoMapper.toEntity(productInfoDto);
        if (productInfo.getIsPublished()==1){
            return -10;
        }
        if (Objects.equals(info.getContractState(), "未发布")){
            return -11;
        }


        BatchProductDto batchProductDto = new BatchProductDto();
        batchProductDto.setInfoId(productInfo.getInfoId());
        batchProductDto.setProductCode(productInfo.getProductCode());
        batchProductDto.setProductType(productInfo.getProductType());
        batchProductDto.setProductDesc(productInfo.getProductDesc());
        batchProductDto.setBatchPlanId("-1");
        batchProductDto.setIsStandard(BigDecimal.valueOf(productInfo.getIsStandard()));
        batchProductDto.setProjectName(info.getProjectName());
        batchProductDto.setProjectCode(info.getProjectCode());



        batchProductDto.setEngineer(productInfo.getEngineer());
        System.out.println("是否为标准柜体：" + productInfo.getIsStandard());
        if (productInfo.getIsStandard() == 1) { //标准柜体
            batchProductDto.setStandardProductCode(productInfo.getStandTypeCode());
            StandProduct standProduct = standProductRepository.findStandProductByStandTypeCodeAndDelete(productInfo.getStandTypeCode(),0);
//            if (standProduct == null ) throw new BeadminException("未找到该标准柜体");
//            //设置图纸 BOM 和BOP
//            standFileInfoRepository.findStandFileInfoByStandTypeIdAndCategoryAndStatusAndDelete(standProduct.getId(),"图纸",1,0);
//            if (standProduct.getStandBomFileCode() != null) {
//                //将BOM添加到这个表中 productBomOverview
//
//                batchProductDto.setBomId(standProduct.getStandBomFileCode());
//                batchProductDto.setIsBomUploaded(BigDecimal.valueOf(1));
//            }
//            if (standProduct.getStandDrawingFileCode() != null) {
//                //将图纸添加到这个表中 productDrawingOverview
//
//                batchProductDto.setDrawingId(standProduct.getStandDrawingFileCode());
//                batchProductDto.setIsDrawingUploaded(BigDecimal.valueOf(1));
//            }
            if (standProduct.getBopCode() != null) {

                batchProductDto.setBopCode(standProduct.getBopCode());
                batchProductDto.setIsBomUploaded(BigDecimal.valueOf(1));
                // 将每道工序添加到这个表中 productManufactOverview

            }
//            if (batchProductDto.getBomId() != null && batchProductDto.getDrawingId() != null && batchProductDto.getBopCode() != null) {
//                batchProductDto.setReviewState(BigDecimal.valueOf(1));
//            }
//            //            batchProductxDto
        } else { // 非标柜体也给他挂一个工艺路径 默认的 //
            BopTotal defaultBop = bopTotalService.getDefaultBopTotal();
            batchProductDto.setBopCode(defaultBop.getBopCode());
        }

        BatchProduct batchProduct = batchProductMapper.toEntity(batchProductDto);
        batchProductRepository.save(batchProduct);
        productInfo.setIsPublished(1);
        productInfoRepository.save(productInfo);

        return 0;
    }
    @Override
    public int releaseProductInfoAll(List<ProductInfo> productInfos) {
        if (productInfos.size()==0) return -12;
        int presults = -10; //所有都是发布的状态
        for (ProductInfo productInfo : productInfos) {
            int presult = releaseProductInfo(productInfo);
            if (presult == -11){
                return presult;
            }
            if (presult == 0) {
                presults = 0;//只要有一个未发布，就可以请求成功。
            }
        }
        return presults;
    }

    @Override
    public List<ProductInfo> addProductInfos(HttpServletRequest request, ProductInfosDto productInfosDto) {
        if (productInfosDto.getIsStandard().intValue() == 1) { // 检查标准轨是否有问题
            standProductService.checkStandProduct(productInfosDto.getStandTypeCode());
        }

        UserEx userEx = userService.viewBaseInfo(request);


        System.out.println("productInfosDto:"+productInfosDto);
//        String productCodePrefix = serialNumberService.getNextSnByCode("ProductCodePrefix");
        List<ProductInfo> productInfos = new ArrayList<>();

        DictType type = dictTypeService.getDictTypeByName("柜体类型");
        DictData data = dictDataRepository.findDictDataByDictTypeIdAndKeyName(type.getId(), productInfosDto.getProductType());
        String typevalue = data.getKeyValue();
        Info infoByIdAndDelete = infoRepository.findInfoByIdAndDelete(productInfosDto.getInfoId(), 0);
//        List<String> names = teamInfoService.getNameByInfoIdAndType(infoByIdAndDelete.getId(), "技术人员");
//        String engineer = String.join(",",names);
//
        // 对非标柜体设置工程师
//        if (productInfosDto.getIsStandard().intValue() == 0){
//            engineer = productInfosDto.getEngineer();
//        }

//        String engineer = productInfosDto.getEngineer();

        for (int i = 0; i < productInfosDto.getProductQty(); i++) {
            ProductInfo productInfo = new ProductInfo();
            productInfo.setInfoId(productInfosDto.getInfoId());
            productInfo.setIsStandard(productInfosDto.getIsStandard().intValue());
            productInfo.setProductType(productInfosDto.getProductType());
            productInfo.setProjectName(productInfosDto.getProjectName());
            productInfo.setProductDesc(productInfosDto.getProductDesc());
            productInfo.setEngineer(productInfosDto.getEngineer());
            productInfo.setMemo(productInfosDto.getMemo());
            // 物料主数据编码和名称
            productInfo.setMaterialCode(productInfosDto.getMaterialCode());
            productInfo.setMaterialName(productInfosDto.getMaterialName());
            if (productInfo.getIsStandard() != 1) {
                productInfo.setStandTypeCode(productInfosDto.getProductCode());
            } else {
                productInfo.setStandTypeCode(productInfosDto.getStandTypeCode());
            }

            System.out.println("标准柜体编码有没有传输过来：" + productInfo.getStandTypeCode());

//            if (productInfosDto.getIsStandard().intValue()==0){

            String bpCode = serialNumberService.getNextSnByCode(infoByIdAndDelete.getId() + "_P_Code");
            if (bpCode == null) {
                bpCode = serialNumberService.getNextSnByCode("ProductCodePrefix");
            }
            // 柜体编码
            productInfo.setProductCode(infoByIdAndDelete.getProjectCode()+".001."+typevalue+"."+bpCode);



//            }
//            }else if (productInfosDto.getIsStandard().intValue()==1){
//                productInfoDto.setStandTypeCode(productInfosDto.getStandTypeCode());
//                productInfoDto.setProductCode(productInfosDto.getStandTypeCode()+productCodePrefix+"-"+String.format("%03d",i+1));
//            }
            productInfos.add(productInfo);
//            addProductInfo(productInfoDto);
        }
        //productInfoRepository.saveAll(productInfos);
        List<ProductInfo> productInfos1 = productInfoRepository.saveAll(productInfos);

//        System.out.println("productTotalInfos.get(1)"+productTotalInfos.get(0).toString())
        // 发布柜体信息，
        releaseProductInfoAll(productInfos);
//        infoService.genenateProductAll(productInfos);

        return productInfos1;
    }
    @Override
    public int updateProductInfo(ProductInfoDto productInfoDto) {
        BatchProduct batchProduct = batchProductRepository.findBatchProductByProductCodeAndDelete(productInfoDto.getProductCode(), 0);
        if (batchProduct == null) throw new BeadminException("未找到该柜体");

        if (batchProduct.getState()!= 0) { // 该柜体已下发，无法无法修改信息
            throw new BeadminException("该柜体已下发，无法无法修改信息");
        }


        // 更新柜体信息
        ProductInfo productInfo = productInfoRepository.findProductInfoById(productInfoDto.getId());
//            if (productInfo.getIsPublished()==1) throw new BeadminException("该柜体已发布，无法无法修改信息");
        productInfo = productInfoMapper.toEntity(productInfoDto);
        productInfo.setStandTypeCode(productInfo.getStandTypeCode());
        productInfoRepository.save(productInfo);
        // 更新批次柜体信息
        batchProductPdService.updateBatchProduct(productInfo);
        return 0;
    }

    @Override
    public List<String> getProjectTeamEngineers(String infoId) {

        return teamInfoService.getNameByInfoIdAndType(infoId,"技术工程师");

    }

}
